<?php

namespace WeChat\Controller;

use Think\Controller;
use Think\Log;

class BaseController extends Controller {

    protected $appid = false;
    protected $openid = false;
    protected $wechat = false;
    protected $access_token = false;
    protected $cart = false;
    protected $category = false;

    protected function _initialize() {

        #判段是否是在微信中打开
        /**
          if (!$this->isweixin()) {
          header("Content-type:text/html;charset=utf-8");
          exit("请使用微信打开");
          }
         * */
        //读取数据库中的配置
        $config = S('DB_CONFIG_DATA');

        if (!$config) {

            $config = D('SystemConfig')->lists();

            S('DB_CONFIG_DATA', $config);
        }

        C($config); //添加配置

        if (!C('TOGGLE_WEB_SITE')) {

            $this->error('站点已经关闭，请稍后访问~');
        }

        $this->assign('meta_keywords', C('WEB_SITE_KEYWORD'));
        $this->assign('meta_description', C('WEB_SITE_DESCRIPTION'));

        $w = D('Wechat')->find(1);

        $option['token'] = $w['token'];
        $option['appid'] = $w['appid'];
        $option['secret'] = $w['secret'];
        $option['aeskey'] = $w['encodingaeskey'];
        $option['mch_id'] = $w['mch_id'];
        $option['payKey'] = $w['paykey'];
        Log::write("Wechat Init Option:" . json_encode($option));

        $this->wechat = new \Common\WeChat\Wechat($option); //实例化wechat微信类库

        $this->cart = new \Common\Util\Cart(); //实例化购物车类

        $this->appid = $w['appid'];

        $this->assign('cart_count', $this->cart->getNum());

        //初始化-首页分类专区
        $map['status'] = 1;

        $cateogry = D('Category')->where($map)->select();

        $this->assign('category', $cateogry);


        //JS分享接口参数初始化
        $this->wechat->getToken();

        $timestamp = time();

        $nonceStr = rand(100000, 999999);

        $jsapi_ticket = S('jsapi_ticket');

        if (!$jsapi_ticket) {

            $jsapi_ticket = $this->wechat->getJsapiTicket();

            if ($jsapi_ticket) {

                S('jsapi_ticket', $jsapi_ticket, 6000);
            }
        }

        Log::write('__SELF__:' . C('WEB_SITE_DOMAIN') . __SELF__);

        $params = array();

        $params['jsapi_ticket'] = $jsapi_ticket;

        #获取当前页面的网址
        $params['url'] = C('WEB_SITE_DOMAIN') . __SELF__;

        $params['timestamp'] = "$timestamp";

        $params['noncestr'] = "$nonceStr";

        $jsSign = $this->wechat->genSha1Sign($params);

        $this->assign("jsappid", $this->appid);

        $this->assign("jstimestamp", $timestamp);

        $this->assign("jsnonceStr", $nonceStr);

        $this->assign("jsSign", $jsSign);

        $this->assign("fxidentify", is_login_wechat());


        //分享锁定用户，需要在公众平台中添加js安全域名配置
        /**    $fxidentify = I('fxidentify');

          if ($fxidentify) {

          $this->login(TRUE, $fxidentify);
          }
         * */
    }

    /**
     * 
      检测是否是微信
     * 
     * */
    protected function isweixin() {

        $user_agent = $_SERVER['HTTP_USER_AGENT'];

        if (strpos($user_agent, 'MicroMessenger') === false) {

            return FALSE;
        } else {

            return TRUE;
        }
    }

    /*
     * 登录
     * 
     * &force 强制获取信息
     * 
     * $oData内容
     * { "access_token":"ACCESS_TOKEN",
      "expires_in":7200,
      "refresh_token":"REFRESH_TOKEN",
      "openid":"OPENID",
      "scope":"SCOPE"
      }
     */

    protected function login($force = TRUE, $id = 0) {

        $uid = is_login_wechat();

        if ($uid && !$force) {

            return $uid;
        }

        /*         * 获取用户微信网页授权信息* */
        $oData = session('oData'); //网页获取到的用户信息

        $isValid = false;

        if ($oData) {

            //检测网页授权access_token是有有效，如果失效则重新取值
            $isValid = $this->wechat->checkOAuthAccessToken($oData);

            if (!$isValid) {

                $oData = $this->wechat->getOauthAccessToken();

                session('oData', $oData);
            }
        } else {

            if (!isset($_GET['code']) && !$isValid) {

                Log::write("nocode");

                #获取当前页面的全链接
                $url = C('WEB_SITE_DOMAIN') . __SELF__;

                //刷新当前页面，再次获取到code
                redirect($this->wechat->getOAuthRedirect($url, "kmeen", "snsapi_userinfo"));
            } else {

                #上面刷新后重新获取code
                Log::write("code:" . $_GET['code']);
                //获取code码，以获取openid
                $oData = $this->wechat->getOauthAccessToken();

                session('oData', $oData);
            }
        }

        /** 获取用户微信网页授权信息 * */
        $this->openid = $oData['openid'];

        $this->access_token = $oData['access_token'];

        //网页授权获取获取用户信息，使用网页授权的access_token
        $userInfo = $this->wechat->getOauthUserInfo($this->access_token, $this->openid);

        Log::write('member info :' . json_encode($userInfo));

        $data['openid'] = $this->openid;

        if ($userInfo) {

            $data['nickname'] = $userInfo['nickname'];
            $data['nickname']= preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $data['nickname']);
            $data['info'] = json_encode($userInfo);
        }

        #$id作为推荐人id处理后面会员微信注册逻辑
        if ($id) {

            $data['id'] = $id;
        }

        return D("Member")->login($data);
    }

}
